﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace 餐饮管理系统
{
    public partial class  MainWindow : Window
    {
        private Button[] staffStarButtons= new Button[5];
        /// <summary>
        /// 将选中的员工信息装载到右边的“RenyuanScrollView”中
        /// </summary>
        private void loadStaffSelected()
        {
            //找到被选中的人的id
            ListBoxItem staff = RenyuanListBox.SelectedItem as ListBoxItem;
            if (staff == null)
                return;
            string staffInfo = staff.Content.ToString().Trim();
            string id = staffInfo.Substring(0,staffInfo.IndexOf(":")).Trim();

            string sql = "select * from StaffTable where id = '" + id + "'";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            while (dataReader.Read())
            {
                WorkNumber.Text = dataReader[0].ToString().Trim();
                PersonName.Text = dataReader[1].ToString().Trim();
                MobilePhoneTextBox.Text = dataReader[3].ToString().Trim();
                HomePhoneTextBox.Text = dataReader[4].ToString().Trim();
                AddressTextBox.Text = dataReader[5].ToString().Trim();
                EmailTextBox.Text = dataReader[6].ToString().Trim();
                JobTextBox.Text = dataReader[7].ToString().Trim();
                string datetime = dataReader[8].ToString();
                StartTimeTextBox.Text = datetime.Substring(0,datetime.IndexOf(' '));
                ContractLimitTextBox.Text = dataReader[9].ToString().Trim();
                SalaryTextBox.Text = dataReader[10].ToString().Trim();
                RemarkTextBox.Text = dataReader[11].ToString().Trim();

                int grade = dataReader.GetInt32(2);
                setStaffGrade(grade);

                if (dataReader[13] != null && !dataReader[13].ToString().Equals(""))
                {
                    StaffPhoto.Source = DatabaseConnect.ByteArrayToBitmapImage(dataReader[13] as Byte[]);
                    StaffAddPhotoButton.Opacity = 0;
                }
                else 
                {
                    StaffPhoto.Source = null;
                    StaffAddPhotoButton.Opacity = 0.5;
                }
            }
            dataReader.Close();
            RenyuanScrollViewer.ScrollToTop();
        }

        private void InitializeStaffStarButtons()
        {
            StaffStarBar.ApplyTemplate();
            for (int i = 0; i < 5; i++)
            {
                string name = "s" + (i + 1);
                staffStarButtons[i] = StaffStarBar.Template.FindName(name, StaffStarBar) as Button;
            }
        }

        public void setStaffGrade(int grade)
        {
            if (grade < 0 || grade > 5)
            {
                return;
            }

            for (int i = 0; i < 5; i++)
            {
                staffStarButtons[i].Visibility = i < grade ? Visibility.Visible : Visibility.Hidden;
            }

        }

        private int getStaffGrade()
        {
            int grade = 0;
            for (int i = 0; i < 5; i++)
            {
                if (staffStarButtons[i].Visibility == Visibility.Visible)
                {
                    grade++;
                }
            }
            return grade;
        }

        private void loadStaffs(int selectedIndex = 0)
        {
            ListBoxItem branch = CenterListBox.SelectedItem as ListBoxItem;

            if (branch == null)
                return;
            
            string branchName = branch.Content.ToString().Trim();
            string sql = "select id, name from StaffTable where branch_name = '" + branchName + "'";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            RenyuanListBox.Items.Clear();
            int count = 0;
            while (dataReader.Read())
            {
                count++;
                string staffInfo = string.Format("{0,3}: {1}",dataReader[0].ToString().Trim(), dataReader[1].ToString().Trim());
                ListBoxItem item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
                item.Content = staffInfo;
                RenyuanListBox.Items.Add(item);
            }
            dataReader.Close();

            if (count == 0)
            {
                RenyuanScrollViewer.Visibility = Visibility.Hidden;
            }
            else
            {
                RenyuanScrollViewer.Visibility = Visibility.Visible;
            }
            if (selectedIndex < 0 || selectedIndex >= RenyuanListBox.Items.Count)
                selectedIndex = 0;

            if (this.RenyuanListBox.Items.Count > 0)
            {
                (this.RenyuanListBox.Items[selectedIndex] as ListBoxItem).IsSelected = true;
                RenyuanListBox.ScrollIntoView(RenyuanListBox.Items[selectedIndex]);
            }
        }


        private void Renyuan_saveButton_Click(object sender, RoutedEventArgs e)
        {
            if (!MobilePhoneRegex.IsMatch(MobilePhoneTextBox.Text))
            {
                MessageBox.Show("移动电话输入错误！");
                return;
            }
            else if (!HomePhoneRegex.IsMatch(HomePhoneTextBox.Text))
            {
                MessageBox.Show("住宅电话输入错误！");
                return;
            }
            else if (!EmailRegex.IsMatch(EmailTextBox.Text))
            {
                MessageBox.Show("电子邮箱输入错误！");
                return;
            }
            else if (!DateRegex.IsMatch(StartTimeTextBox.Text))
            {
                MessageBox.Show("工作开始时间输入错误！");
                return;
            }
            else if (!SalaryRegex.IsMatch(SalaryTextBox.Text))
            {
                MessageBox.Show("工资金额输入错误！");
                return;
            }

            string sql = "update StaffTable "
                       + "set name = '" + PersonName.Text + "',"
                       + "    score = " + getStaffGrade() + ","
                       + "    mobile_phone = '" + MobilePhoneTextBox.Text + "',"
                       + "    home_phone = '" + HomePhoneTextBox.Text + "',"
                       + "    address = '" + AddressTextBox.Text + "',"
                       + "    email = '" + EmailTextBox.Text + "',"
                       + "    position = '" + JobTextBox.Text + "',"
                       + "    start_time = '" + StartTimeTextBox.Text + "',"
                       + "    contract_limit = '" + ContractLimitTextBox.Text + "',"
                       + "    salary = '" + SalaryTextBox.Text + "',"
                       + "    remark = '" + RemarkTextBox.Text + "' "
                       + "where id = " + WorkNumber.Text;
            databaseConnect.ExecuteQuery(sql);

            try
            {
                if (StaffPhoto.Source != null)
                {
                    FileStream fs = new FileStream(StaffPhoto.Source.ToString().Substring(8), FileMode.Open, FileAccess.Read);
                    Byte[] imageByte = new Byte[fs.Length];
                    fs.Read(imageByte, 0, Convert.ToInt32(fs.Length));
                    fs.Close();
                    sql = "update StaffTable set photo = @imgfile where id = " + WorkNumber.Text;
                    SqlParameter par = new SqlParameter("@imgfile", SqlDbType.Image);
                    par.Value = imageByte;
                    databaseConnect.ExecuteQuery(sql, par);
                }
            }
            catch (Exception)
            {
            }
            loadStaffs(RenyuanListBox.SelectedIndex);
        }

        private int getStaffNumber()
        {
            string sql = "select count(id) from StaffTable";
            object buffer = databaseConnect.ExecuteScaler(sql);
            if (buffer == null)
            {
                return -1;
            }
            else
            { 
                return (int)buffer;
            }
        }

        private int getStaffNumber(string branchName)
        {
            string sql = "select count(id) from StaffTable where branch_name = '" + branchName + "'";
            object buffer = databaseConnect.ExecuteScaler(sql);
            if (buffer == null)
            {
                return -1;
            }
            else
            {
                return (int)buffer;
            }
        }

        private void Renyuan_addButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ListBoxItem branch = CenterListBox.SelectedItem as ListBoxItem;
            if (branch == null)
                return;
            string branchName = branch.Content.ToString().Trim();
            string sql = "insert into StaffTable(branch_name) "
                        + "values('" + branchName + "'" + ")";
            databaseConnect.ExecuteQuery(sql);
            loadStaffs(getStaffNumber(branchName) - 1);
        }

        private void StaffDeleteButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ListBoxItem branch = CenterListBox.SelectedItem as ListBoxItem;
            if (branch == null)
                return;
            string branchName = branch.Content.ToString().Trim();
            string sql = "delete from StaffTable where id = "+WorkNumber.Text;
            databaseConnect.ExecuteQuery(sql);
            loadStaffs(getStaffNumber(branchName) - 1);
        }

        private void RenyuanListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            loadStaffSelected();
        }

        private void StaffAddPhotoButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Button addButton = sender as Button;
            addButton.ApplyTemplate();
            //Image staffPhoto = addButton.Template.FindName("image", addButton) as Image;

            //创建＂打开文件＂对话框
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            //设置文件类型过滤
            dlg.Filter = "图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg";

            // 调用ShowDialog方法显示＂打开文件＂对话框
            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                //获取所选文件名并在FileNameTextBox中显示完整路径
                string filename = dlg.FileName;

                //在image1中预览所选图片
                BitmapImage image = new BitmapImage(new Uri(filename));
                StaffPhoto.Source = image;
                StaffAddPhotoButton.Opacity = 0;
            }

        }


	}
}

